<template>
	<div class="bg">
		<el-card class="form-card">
			<div slot="header" class="clearfix">
				<span>登录</span>
			</div>
			<el-form label-position="right" label-width="80px" :model="form" :rules="rules" ref='form'>
				<el-form-item label="账号" prop="username">
					<el-input v-model="form.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="form.password" type="password"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click='handleLogin'>登录</el-button>
				</el-form-item>
			</el-form>
			<div class="action-box">
				<el-link type='info' href='#/register'>注册账号</el-link>
				<el-link type='info' href='#/'>忘记密码?</el-link>
			</div>
		</el-card>

	</div>
</template>
<script>
	import { Admin } from '@/api';
	export default {
		data() {
			return {
				form: {
					username: '',
					password: '',
				},
				rules: {
					username: [
						{ type: 'string', required: true, message: '请输入账户名称', trigger: 'blur' },
						{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					password: [{ required: true, message: '请输入密码', trigger: 'blur' },
						{ pattern: /^\d{3,15}$/, message: '长度在 3 到 15 个数字', trigger: 'blur' },
					],
				}
			};
		},
		methods: {
			handleLogin() {
				//表单验证
				this.$refs.form.validate(async (valid) => {
					if (valid) {
						//发送ajax
						let { status, msg, data } = await Admin.login({ ...this.form });
						if (status) {
							//缓存数据
							sessionStorage.id = data.id;
							sessionStorage.role = data.role;
							sessionStorage.token = data.token;
							//提示成功
							this.$message.success(msg)
							//跳转页面
							let { redirect } = this.$route.query;
							if (redirect) {
								this.$router.replace(redirect)
							}
							this.$router.replace('/goods/list')
						} else {
							//提示失败
							this.$message.error(msg)
						}
					}
				});
			},
		},
	}
</script>

<style lang="less" scoped>
	.bg {
		position: relative;
		background-image: url(~@/assets/img/login/bg.jpg);
		background-repeat: no-repeat;
		width: 100vw;
		height: 100vh;
		background-size: cover;

		.form-card {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 100px;
			width: 360px;
		}

		.action-box {
			display: flex;
			justify-content: space-between;
		}

	}
</style>
